from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))  # 加src路径

from crud import read_patients, create_patient, update_patient, delete_patient  # 患者CRUD
from crud import read_appointments, create_appointment, update_appointment, delete_appointment  # 预约CRUD
from crud import read_medical_records, create_medical_record, update_medical_record, delete_medical_record  # 记录CRUD
from crud import read_prescriptions, create_prescription, update_prescription, delete_prescription  # 处方CRUD
from queries import calculate_revenue_per_department  # 复杂查询
from typing import Optional

app = FastAPI(title="Hospital API")  # API启动

# 患者输入格式（像表单）
class PatientCreate(BaseModel):
    name: str
    dob: str
    contact: Optional[str] = None
    email: str
    medical_history: Optional[str] = None

# 预约输入格式
class AppointmentCreate(BaseModel):
    patient_id: int
    staff_id: int
    room_id: int
    date: str
    time: str

# 医疗记录输入格式
class MedicalRecordCreate(BaseModel):
    appointment_id: int
    diagnosis: str
    symptoms: Optional[str] = None
    observations: Optional[str] = None

# 处方输入格式
class PrescriptionCreate(BaseModel):
    appointment_id: int
    notes: Optional[str] = None

# ========== 患者端点 ==========
# 1. GET: 列出患者 (搜索)
@app.get("/api/patients")
def get_patients(search: Optional[str] = None):
    try:
        data = read_patients(search_name=search)  # 用队友函数
        return {"patients": data}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# 2. GET: 单个患者
@app.get("/api/patients/{id}")
def get_patient(id: int):
    data = read_patients()  # 找ID
    patient = next((p for p in data if p[0] == id), None)
    if not patient:
        raise HTTPException(status_code=404, detail="患者不存在")
    return {"patient": patient}

# 3. POST: 创建患者
@app.post("/api/patients", status_code=201)
def create_patient_api(patient: PatientCreate):
    try:
        create_patient(patient.name, patient.dob, patient.contact, patient.email, patient.medical_history)
        return {"message": "患者创建成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# 4. PUT: 更新患者
@app.put("/api/patients/{id}")
def update_patient_api(id: int, patient: PatientCreate):
    try:
        update_patient(id, patient.name, patient.dob, patient.contact, patient.email, patient.medical_history)
        return {"message": "患者更新成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# 5. DELETE: 删除患者
@app.delete("/api/patients/{id}")
def delete_patient_api(id: int):
    try:
        delete_patient(id)
        return {"message": "患者删除成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# ========== 预约端点 ==========
# GET: 列出预约 (过滤日期)
@app.get("/api/appointments")
def get_appointments(by_date: Optional[str] = None):
    try:
        data = read_appointments(by_date=by_date)  # 队友函数
        return {"appointments": data}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# POST: 创建预约
@app.post("/api/appointments", status_code=201)
def create_appointment_api(appointment: AppointmentCreate):
    try:
        create_appointment(appointment.patient_id, appointment.staff_id, appointment.room_id, appointment.date, appointment.time)
        return {"message": "预约创建成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# PUT: 更新预约 (日期/时间)
@app.put("/api/appointments/{id}")
def update_appointment_api(id: int, date: Optional[str] = None, time: Optional[str] = None):
    try:
        update_appointment(id, date, time)
        return {"message": "预约更新成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# DELETE: 删除预约
@app.delete("/api/appointments/{id}")
def delete_appointment_api(id: int):
    try:
        delete_appointment(id)
        return {"message": "预约删除成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# ========== 医疗记录端点 ==========
# GET: 列出医疗记录 (按患者)
@app.get("/api/medical_records")
def get_medical_records(patient_id: Optional[int] = None):
    try:
        data = read_medical_records(patient_id=patient_id)
        return {"medical_records": data}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# POST: 创建医疗记录
@app.post("/api/medical_records", status_code=201)
def create_medical_record_api(record: MedicalRecordCreate):
    try:
        create_medical_record(record.appointment_id, record.diagnosis, record.symptoms, record.observations)
        return {"message": "医疗记录创建成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# PUT: 更新医疗记录
@app.put("/api/medical_records/{id}")
def update_medical_record_api(id: int, diagnosis: Optional[str] = None, symptoms: Optional[str] = None, observations: Optional[str] = None):
    try:
        update_medical_record(id, diagnosis, symptoms, observations)
        return {"message": "医疗记录更新成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# DELETE: 删除医疗记录
@app.delete("/api/medical_records/{id}")
def delete_medical_record_api(id: int):
    try:
        delete_medical_record(id)
        return {"message": "医疗记录删除成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# ========== 处方端点 ==========
# GET: 列出处方 (按预约)
@app.get("/api/prescriptions")
def get_prescriptions(appointment_id: Optional[int] = None):
    try:
        data = read_prescriptions(appointment_id=appointment_id)
        return {"prescriptions": data}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# POST: 创建处方
@app.post("/api/prescriptions", status_code=201)
def create_prescription_api(prescription: PrescriptionCreate):
    try:
        create_prescription(prescription.appointment_id, prescription.notes)
        return {"message": "处方创建成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# PUT: 更新处方
@app.put("/api/prescriptions/{id}")
def update_prescription_api(id: int, notes: Optional[str] = None):
    try:
        update_prescription(id, notes)
        return {"message": "处方更新成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# DELETE: 删除处方
@app.delete("/api/prescriptions/{id}")
def delete_prescription_api(id: int):
    try:
        delete_prescription(id)
        return {"message": "处方删除成功"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# 加1复杂查询端点 (规范要求)
@app.get("/api/revenue")
def get_revenue():
    data = calculate_revenue_per_department()
    return {"revenue_per_department": data}

# 运行服务器 (终端用uvicorn)
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)